import { Subject } from 'rxjs';
import { Component, EventEmitter, OnInit, Output, ViewChild, ElementRef, Input } from '@angular/core';

@Component({
    selector: 'tree-toolbar',
    templateUrl: './ide-tree-toolbar.component.html',
    styleUrls: ['ide-tree-toolbar.component.css']
})
export class IdeTreeToolbarComponent implements OnInit {

    textChange = new Subject();
    @Input() enableRefresh = false;

    @Output() menuClick = new EventEmitter();
    @Output() refresh = new EventEmitter();

    @ViewChild('toolbar') toolbarEl: ElementRef<any>;
    @ViewChild('searchInput') searchInput: ElementRef<any>;

    isPanelOpen = false;
    pos = { left: 0, top: 0 };

    _showId = false;

    isExpanded = true;
    /** 输入法输入过程标识 */
    searchFlag = true;

    /** 暂存搜索文本 */
    searchValue: string;

    constructor() { }

    ngOnInit(): void { }


    togglePanel($event) {

        const toolbarElRect = this.toolbarEl.nativeElement.getBoundingClientRect();
        this.pos = {
            left: toolbarElRect.width + toolbarElRect.left - 200,
            top: toolbarElRect.height + toolbarElRect.top
        };

        this.isPanelOpen = !this.isPanelOpen;
    }

    hidePanel($event: MouseEvent) {
        $event.stopPropagation();
        this.isPanelOpen = false;
    }

    clearInput($event: MouseEvent, searchInput: any) {
        $event.stopPropagation();
        searchInput.value = '';
        this.textChange.next({ event: $event, val: '' });
    }

    onMenuItemClick($event, key: string) {
        if (key) {
            key = key.toUpperCase();
        }

        const p = { event: $event, action: { key, value: false } };

        switch (key) {
            case 'SHOWID':
                this._showId = !this._showId;
                p.action.value = this._showId;
                break;
        }
        this.menuClick.emit(p);
    }


    toggleNodes($event) {
        this.isExpanded = !this.isExpanded;
        this.onMenuItemClick($event, this.isExpanded ? 'expandall' : 'collapseall');
    }

    onRefresh() {
        this.refresh.emit();
    }

    onTextChange($event) {
        const val = $event.target.value;
        this.searchValue = val;
        if (!this.searchFlag) {
            return;
        }
        this.textChange.next({ event: $event, val });
    }

    onSearchChangeFlag(value) {
        this.searchFlag = value;
        // 拼音按空格后input的执行时间早于compositionend，故重新触发一次
        if (value) {
            this.textChange.next({ val: this.searchValue });
        }
    }
    /**
     * 监听回车事件
     * @param $event 事件
     */
    onTextKeyup($event) {
        if ($event.which === 13) {
            this.onTextChange($event);
        }
    }
}
